<!-- 表格组件 -->
<template>
    <el-table 
        :stripe="stripe" 
        ref="pcTable" 
        size="default" 
        class="pcTable" 
        :data="data" 
        :height="tableHeight"
        :max-height="maxHeight"
        :showSummary="showSummary"
        :showMethod ="showMethod"
        :style="{ width: width }" 
        v-loading="loading" 
        @selection-change="selectionChange"
        header-row-class-name="pc-table-head-class" 
        row-class-name="pc-table-row-class" 
        empty-text="暂无数据"
        element-loading-text="数据加载中" 
        @row-click="rowClick"
        @sort-change="sortChange">
        <el-table-column v-if="isEdit" type="selection" width="55"> </el-table-column>
        <el-table-column type="index" label="序号" fixed="left" v-if="showIndex" align="center" width="50"></el-table-column>
        <template v-for="item in column">
            <!-- 时间 yyyy-mm-dd -->
            <el-table-column v-if="item.type === 'date'" v-bind="{ ...item, prop: item.key }">
                <template #default="scope"> <i v-if="scope.row[item.key]" class="el-icon-time"></i> {{
                formatDate(scope.row[item.key]) }} </template>
            </el-table-column>
            <!-- 时间 yyyy-mm-dd HH:MM:SS -->
            <el-table-column v-else-if="item.type === 'dateTime'"
                v-bind="{ ...item, key: item.key + 1, prop: item.key }">
                <template #default="scope"> <i v-if="scope.row[item.key]" class="el-icon-time"></i> {{
                scope.row[item.key] == 0 ? '-' : formatDateTime(scope.row[item.key]) }} </template>
            </el-table-column>
            <!-- 数字 -->
            <el-table-column v-else-if="item.type === 'number'"
                v-bind="{ ...item, key: item.key + 2, align: 'right', prop: item.key }">
                <template #default="scope">
                    <span class="pc-table-number">
                        {{ isNull(scope.row[item.key]) }}
                    </span>
                </template>
            </el-table-column>
            <!-- 价格 -->
            <el-table-column v-else-if="item.type === 'price'"
                v-bind="{ ...item, key: item.key + 3, align: 'right', prop: item.key }">
                <template #default="scope">
                    <span :class="scope.row[item.key] > 0 ? 'price-red-bold' : 'price-black-bold'">
                        {{ isNull(scope.row[item.key]) }}
                    </span>
                </template>
            </el-table-column>
            <!-- 复制 -->
            <el-table-column v-else-if="item.type === 'copy'" v-bind="{ ...item, key: item.key + 4, prop: item.key }">
                <template #default="scope">
                    <span class="one-row" :style="{ color: item.color }">
                        <el-icon v-if="scope.row[item.key]" class="el-copy" @click="copyText(scope.row[item.key])">
                            <DocumentCopy />
                        </el-icon>
                        <span>{{ isNull(scope.row[item.key]) }}</span>
                    </span>
                </template>
            </el-table-column>
            <!-- 长文字显示 -->
            <el-table-column v-else-if="item.type === 'tooltip'"
                v-bind="{ ...item, key: item.key + 5, prop: item.key }">
                <template #default="scope">
                    <el-tooltip effect="dark" popper-class="table-tooltip" :disabled="!scope.row[item.key]"
                        :open-delay="500" :content="scope.row[item.key].toString()" placement="top-start">
                        <span class="one-row" :style="{ color: item.color }">
                            {{ isNull(scope.row[item.key]) }}
                        </span>
                    </el-tooltip>
                </template>
            </el-table-column>
            <!-- 插槽 -->
            <el-table-column v-else v-bind="{ ...item, key: item.key + 6, prop: item.key }">
                <template #header v-if="item.customHeader">
                    {{ item.label }}
                    <el-tooltip class="box-item" effect="dark" :content="item.customHeader" placement="bottom">
                        <el-icon>
                            <QuestionFilled />
                        </el-icon>
                    </el-tooltip>
                </template>
                <template #default="scope">
                    <span v-if="item.type !== 'slot'" :style="{ color: item.color }">
                        {{ item.front }}
                        <span v-if="item.obj" v-html="isNull(item.obj[scope.row[item.key]])"></span>
                        <template v-else>{{ isNull(scope.row[item.key]) }}</template>
                        {{ item.post }}
                    </span>
                    <template v-else>
                        <div class="funClass" v-if="item.key == 'fun'">
                            <slot :name="item.key" :row="scope.row" :index="scope.$index"></slot>
                        </div>
                        <slot v-else :name="item.key" :row="scope.row" :index="scope.$index"></slot>
                    </template>
                </template>
            </el-table-column>
        </template>
    </el-table>
</template>

<script setup lang="ts">
import { ElMessage } from 'element-plus'
const props = defineProps({
    // 表格数据
    data: {
        type: Array,
        default: function () {
            return []
        }
    },
    stripe: {
        type: Boolean,
        default: true
    },
    // 是否可编辑
    isEdit: {
        type: Boolean,
        default: false
    },
    // 表格每行内容
    column: {
        type: Array as () => Array<any>,
        default: function () {
            return []
        }
    },
    // 自定义高度
    height: {
        type: [String, Number],
        default: undefined
    },
    maxHeight: {
        type: [String, Number],
        default: undefined
    },
    width: {
        type: [String, Number],
        default: '100%'
    },
    showSummary: {
        type: Boolean,
        default: false
    },
    showMethod: {
        type: Function,
        default: function () { }
    },
    // 表格加载
    loading: {
        type: Boolean,
        default: false
    },
    showIndex: {
        type: Boolean,
        default: false
    },
    // 表格多选数据
    selectableList: {
        type: Array,
        default: function () {
            return []
        }
    }
})
const pcTable = ref()
const emit = defineEmits(['selectionChange', 'rowClick', 'sortChange'])

const tableHeight = ref<any>(undefined)
onMounted(async () => {
    if (!props.height) {
        getHeight()
    } else {
        await nextTick()
        if (props.height != 'auto') {
            tableHeight.value = props.height
        } else {
            tableHeight.value = undefined
        }
    }
})

// 设置高度
const getHeight = () => {
    if (!props.height) {
        // setTimeout(() => {
        //     tableHeight.value = window.innerHeight - this.$refs.pcTable.$el.offsetTop - 120
        // },50)
    }
}

// 点击事件
const rowClick = (data: any, column: any, enent: any) => {
  if (!enent.path || (enent.path[0].className.indexOf('el-table-column--selection') == -1 && enent.path[1].className.indexOf('el-table-column--selection') == -1)){
    emit('rowClick', data)
  }
}

// 复制文本
const copyText = (text: string) => {
    let oInput: any
    if (document.getElementById('copyInput')) {
        oInput = document.getElementById('copyInput')
    } else {
        oInput = document.createElement('input')
    }
    oInput.value = text
    oInput.id = 'copyInput'
    oInput.className = 'copy-input'
    document.body.appendChild(oInput)
    oInput.select()
    document.execCommand('Copy')
    ElMessage.success('复制成功')
}

// 空文本
const isNull = (value: any) => {
    if (value || value === 0) {
        return value
    } else {
        return '-'
    }
}

// 时间处理
const formatDate = (time: string) => {
    if (time) {
        return parseTime(time, '{y}-{m}-{d}')
    }
    return '-'
}

const formatDateTime = (time: string) => {
    if (time) {
        return parseTime(time)
    }
    return '-'
}

const parseTime = (time: any, cFormat?: string) => {
    if (!time) {
        return null
    }
    const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
    let date
    if (typeof time === 'object') {
        date = time
    } else {
        if (typeof time === 'string') {
            if (/^[0-9]+$/.test(time)) {
                time = parseInt(time)
            } else {
                time = time.replace(new RegExp(/-/gm), '/')
            }
        }

        if (typeof time === 'number' && time.toString().length === 10) {
            time = time * 1000
        }
        date = new Date(time)
    }
    const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay()
    }
    const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
        const value = formatObj[key]
        if (key === 'a') {
            return ['日', '一', '二', '三', '四', '五', '六'][value]
        }
        return value.toString().padStart(2, '0')
    })
    return time_str
}

// 勾选变化
const selectionChange = (data: any) => {
    emit('selectionChange', data)
}

// 全选切换
const toggleAllSelection = () => {
    pcTable.value.toggleAllSelection()
}

// 清除选择
const clearSelection = () => {
    pcTable.value.clearSelection()
}

//触发排序
const sortChange = (column: any) => {
    emit('sortChange', column)
}

defineExpose({
    toggleAllSelection,
    clearSelection
})
</script>
<style lang="scss">
.copy-input {
    position: fixed;
    top: 1000px;
}

.pcTable {
    .pc-table-head-class {
        color: #666;
    }

    .one-row {
        .el-copy {
            vertical-align: middle;
            margin-right: 6px;
            cursor: pointer;
            display: inline-block;
        }

        span {
            vertical-align: middle;
        }
    }
}

.table-btn,
.table-del,
.table-success,
.table-warning {
    color: #3396f8;
    font-size: 12px;
    cursor: pointer;
    display: inline-block;
    margin: 0px 6px;
}

.table-del {
    color: #ff2f01;
}

.table-success {
    color: #5eb135;
}

.table-warning {
    color: #e6a23c;
}
</style>